package chinatelecom.feilong.framework.web.license.service.impl;

import chinatelecom.feilong.framework.common.jpa.DynamicSpecifications;
import chinatelecom.feilong.framework.common.jpa.SearchFilter;
import chinatelecom.feilong.framework.web.license.dao.ILicenseDao;
import chinatelecom.feilong.framework.web.license.dao.ILicenseMainDao;
import chinatelecom.feilong.framework.web.license.dao.ILicenseTemplateDao;
import chinatelecom.feilong.framework.web.license.entity.License;
import chinatelecom.feilong.framework.web.license.entity.LicenseMain;
import chinatelecom.feilong.framework.web.license.entity.LicenseTemplate;
import chinatelecom.feilong.framework.web.license.service.ILicenseService;
import chinatelecom.feilong.framework.web.manager.service.ILicenseManagerService;
import chinatelecom.feilong.framework.web.sys.dao.IUserDao;
import chinatelecom.feilong.framework.web.sys.entity.SysUser;
import chinatelecom.feilong.framework.web.sys.util.UserUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@Transactional
@Service
public class LicenseServiceImpl implements ILicenseService{
     @Resource
     private ILicenseDao iLicenseDao;
     @Resource
     private ILicenseMainDao iLicenseMainDao;
     @Resource
     private ILicenseTemplateDao iLicenseTemplateDao;
     @Resource
     private IUserDao iUserDao;
     @Resource
     private ILicenseManagerService licenseManagerService;
     @Resource
     private ILicenseService licenseService;

     @Override
     public License saveLicense(License license) throws Exception {
          this.checkParam(license);
          LicenseMain licenseMain = license.getLicenseMain();
          String result = licenseService.findSameLicenseName(licenseMain.getSubject());
          if(result == null){
               licenseMain.setSysUser(UserUtils.getCurrentUser());

               licenseMain = iLicenseMainDao.save(licenseMain);

               license.setNotAfter(DateUtils.addDays(license.getNotBefore(), license.getValidity()));
               license.setIssuedDate(new Date());
               license.setLicenseMain(licenseMain);
               license.setRenewTimes(0);

               String path = licenseManagerService.createLicense(license);
               license.setPath(path);
          }else{
               throw new RuntimeException("license的名称不能重复！");
          }
          return iLicenseDao.save(license);
     }

     @Override
     public License renewalLicense(License license) throws Exception {
          this.checkParam(license);
          license.setNotAfter(DateUtils.addDays(license.getNotBefore(), license.getValidity()));
          license.setIssuedDate(new Date());
          license.setRenewTimes(0);
          String path = licenseManagerService.createLicense(license);
          license.setPath(path);
          return iLicenseDao.save(license);
     }

     @Override
     @Transactional(propagation = Propagation.NOT_SUPPORTED)
     public Page<LicenseMain> listPageByParams(Map<String, Object> params, Pageable pageable, String sortName, String sortValue) {
          Page<LicenseMain> licensePage = null;
          if(sortName!=null&&sortValue!=null){
               Integer pageNumber = pageable.getPageNumber();
               Integer pageSize = pageable.getPageSize();
               if(sortValue.equals("asc")) {
                    pageable = new PageRequest(pageNumber,pageSize, Sort.Direction.ASC, sortName);
               }else {
                    pageable = new PageRequest(pageNumber,pageSize,Sort.Direction.DESC, sortName);
               }
          }
          if(params == null){
               licensePage = iLicenseMainDao.findAll(pageable);
          }else{
               Map<String,SearchFilter>  filters = SearchFilter.parse(params);
               Specification<LicenseMain> spec = DynamicSpecifications.bySearchFilter(filters.values());
               licensePage = iLicenseMainDao.findAll(spec, pageable);
          }
          return licensePage;
     }

     @Override
     public List<License> listByMainId(Integer id) {
          if (null == id || id == 0) return null;

          Map<String, Object> params = new HashMap<String, Object>();
          params.put(SearchFilter.Operator.EQ + "_licenseMain.id", id);
          Map<String,SearchFilter>  filters = SearchFilter.parse(params);
          Specification<License> spec = DynamicSpecifications.bySearchFilter(filters.values());

          List<License> list = iLicenseDao.findAll(spec);

          return list;
     }

     @Override
     public void deleteCascade(Integer id) {
          License license = iLicenseDao.findOne(id);
          Integer res = licenseService.findAllBySubjectId(license.getLicenseMain().getId()).size();

          String path = license.getPath();
          boolean flag = false;
          if(path!=null&&!"".equals(path)) {
               flag = deleteFile(path);
          }

          iLicenseDao.delete(id);

          if(res == 1){
               iLicenseMainDao.delete(license.getLicenseMain().getId());
          }
     }

     @Override
     public License findByID(Integer id){
          License license = iLicenseDao.findOne(id);

          return license;
     }

     public boolean deleteFile(String sPath) {
          boolean flag = false;
          File file = new File(sPath);
          // 路径为文件且不为空则进行删除
          if (file.isFile() && file.exists()) {
               file.delete();
               flag = true;
          }
          return flag;
     }

     @Override
     public String findSameLicenseName(String subject) throws Exception {
          String result = iLicenseDao.findSameLicenseName(subject);
          return result;
     }

     @Override
     public LicenseTemplate findByVersion(Integer type) {
          LicenseTemplate licenseTemplate =iLicenseTemplateDao.findOne(type);
          return licenseTemplate;
     }
     @Override
     public SysUser findUserId(String userName) {
          SysUser sysUser =iUserDao.getByUsername(userName);
          return sysUser;
     }

     private void checkParam(License license) throws NullPointerException {

          if (null == license.getLicenseMain()) {
               throw new NullPointerException("licesne名称为空!");
          }

          if (StringUtils.isBlank(license.getLicenseMain().getSubject())) {
               throw new NullPointerException("licesne名称为空!");
          }

          if (StringUtils.isBlank(license.getCpu())) {
               throw new NullPointerException("cpu 序列号为空!");
          }

          if (StringUtils.isBlank(license.getDisk())) {
               throw new NullPointerException("硬盘序列号为空!");
          }

          if (StringUtils.isBlank(license.getIp())) {
               throw new NullPointerException("ip 为空!");
          }

          if (StringUtils.isBlank(license.getMac())) {
               throw new NullPointerException("mac 为空!");
          }

          if (StringUtils.isBlank(license.getMotherboard())) {
               throw new  NullPointerException("主板为空!");
          }

          if (StringUtils.isBlank(license.getSystem())) {
               throw new NullPointerException("系统序列号为空!");
          }

          if (null == license.getLicenseTemplate()) {
               throw new NullPointerException("版本信息为空!");
          }

          if (null == license.getNotBefore()) {
               throw new NullPointerException("开始日期为空!");
          }

          if (null == license.getValidity() || license.getValidity() == 0) {
               throw new  NullPointerException("时长为0!");
          }
     }

     @Override
     public List<License> findAllBySubjectId(Integer subjectId) {
          List list = iLicenseDao.findAllBySubjectId(subjectId);
          return list;
     }
}
